package eip.chapter4.invalidmessage.mule;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.mule.transformers.AbstractTransformer;
import org.mule.umo.transformer.TransformerException;

import eip.chapter4.invalidmessage.Hotel;
import eip.chapter4.invalidmessage.HotelSearchMessage;

/**
 * This transformer transforms a list of hotels to an XML message.
 * 
 * @author nl24167
 */
public class HotelToXMLTransformer extends AbstractTransformer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8157122377256710393L;

	/**
	 * Transform the incoming List of hotels to an XML file.
	 * 
	 * @throws TransformerException
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected Object doTransform(Object src, String encoding) throws TransformerException {
		List<Hotel> hotels = (List<Hotel>) src;
		Document doc = DocumentFactory.getInstance().createDocument();
		Element root = doc.addElement("hotels");
		
		StringWriter output = new StringWriter();
		try {
			IBindingFactory bfact = BindingDirectory.getFactory(HotelSearchMessage.class);
			IMarshallingContext mctx = bfact.createMarshallingContext();
			for (Hotel hotel : hotels) {
				ByteArrayOutputStream bOut = new ByteArrayOutputStream();
				mctx.marshalDocument(hotel, "UTF-8", null, bOut);
				SAXReader reader = new SAXReader();
				Document hotelDoc = reader.read(new ByteArrayInputStream(bOut.toByteArray()));
				root.add(hotelDoc.getRootElement());
			}
			new XMLWriter(output).write(root);
		} catch (Exception e) {
			throw new TransformerException(this, e);
		}
		return output.toString();
	}
}
